package com.itttq.im.controller;

import com.itttq.im.common.constant.Constant;
import com.itttq.im.common.constant.RedisConstant;
import com.itttq.im.model.qo.MsgQo;
import com.itttq.im.model.to.MsgTo;
import com.itttq.im.model.to.PageTo;
import com.itttq.im.service.MsgService;
import com.itttq.im.utils.RedisUtil;
import com.itttq.im.ws.netty.MessageHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("chat")
@Slf4j
public class ChatController {
    @Autowired
    private MsgService msgService;
    @Autowired
    private MessageHandler messageHandler;
    @Value("${fyim.upload.imgPath}")
    private String imgPath;
    @Value("${fyim.upload.imgUrl}")
    private String imgUrl;
    @Autowired
    private RedisUtil redisUtil;

    @GetMapping("/msg")
    public PageTo<MsgTo> findMsg(MsgQo msgQo) {
        return msgService.findMsg(msgQo);
    }

    /**
     * 获取所有用户信息（从缓存获取），后续扩展为获取自己好友信息
     *
     * @return
     */
    @GetMapping("/users")
    public Set<String> findUsers() {
        return redisUtil.members(RedisConstant.getKeyUserOnline());
    }

    /**
     * 获取群组信息，后续扩展为或者自己所在的群组信息
     *
     * @return
     */
    @GetMapping("/groups")
    public Set<String> findGroups() {
        return redisUtil.members(RedisConstant.getKeyGroupId());
    }

    private List<String> converToList(Enumeration<String> uidEnum) {
        List<String> list = new ArrayList<>();
        while (uidEnum.hasMoreElements()) {
            list.add(uidEnum.nextElement());
        }
        return list;
    }

    /**
     * 发送广播消息
     *
     * @return
     */
    @PostMapping("/broadcast")
    public void broadcast(String msg) {
        messageHandler.sendGroupMsg(MsgTo.builder().type(MsgTo.MsgType.BROADCAST.getCode()).body(msg).build());
    }

    @PostMapping("/sendMsg")
    public void sendMsg(@RequestBody @Validated MsgTo msgTo) {
        messageHandler.sendMsg(msgTo);
    }

    /**
     * 上传图片方法
     *
     * @param file
     * @return
     */
    @PostMapping("/uploadImg")
    public String uploadImg(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return null;
        }
        // 获取新的文件名和后缀
        String fileName = System.nanoTime() + file.getOriginalFilename().substring(file.getOriginalFilename().indexOf(Constant.POINT));
        try {
            // 判断文件夹是否存在
            File destDir = new File(imgPath);
            // 如果不存在则创建
            if (!destDir.exists()) {
                destDir.mkdirs();
            }
            file.transferTo(new File(imgPath + fileName));
        } catch (Exception e) {
            log.error("上传异常", e);
        }
        return imgUrl + fileName;
    }
}
